package com.jijia.webbase.controller;

import cn.hutool.json.JSONUtil;
import com.jijia.webbase.config.response.JsonResult;
import com.jijia.webbase.config.security.LoginUser;
import com.jijia.webbase.config.security.SaveLoginUser;
import com.jijia.webbase.domain.User;
import com.jijia.webbase.mapper.UserMapper;
import com.jijia.webbase.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.HashMap;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

// AuthController.java
// 7. 登录接口
@Slf4j
@RestController
public class AuthController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

//    @PostMapping("/login")
//    public JsonResult login(@RequestBody User user) {
//        log.debug("login user: {}", user);
//        // Spring Security认证流程
//        Authentication authentication = null;
//        try {
//            log.debug("Attempting to authenticate user: {}", user.getUserName());
//           authentication = authenticationManager.authenticate(
//                    new UsernamePasswordAuthenticationToken(
//                            user.getUserName(),
//                            user.getUserPassword()
//                    )
//            );
//            log.debug("login 认证结果: {}", authentication);
//
//        } catch (LockedException e) {
//            log.error("User account is locked for user: {}", user.getUserName(), e);
//            return JsonResult.ok("User account is locked");
//        } catch (Exception e) {
//            log.error("Authentication failed for user: {}", user.getUserName(), e);
//            return JsonResult.ok("Authentication failed");
//        }
//
//        // 生成JWT
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//
//        String token = jwtUtil.generateToken(loginUser);
//        loginUser.setToken(token);
//        log.debug("未序列化 {}", loginUser);
//        log.debug("序列化 {}", JSONUtil.toJsonStr(loginUser));
//
//        log.debug("序列化 角色: {}", JSONUtil.toJsonStr(loginUser.getAuthorities().toString()));
//        SaveLoginUser saveLoginUser = new SaveLoginUser();
//        BeanUtils.copyProperties(loginUser,saveLoginUser);
//        // 存储到Redis
//        jwtUtil.storeUserWithToken("token_"+loginUser.getUsername(), saveLoginUser);
//
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token", token);
//
//        return JsonResult.ok(map);
//    }

    @PostMapping("/login")
    public JsonResult login() {
        log.debug("控制器中 ");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 生成JWT
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        String token = jwtUtil.generateToken(loginUser);
        loginUser.setToken(token);
        log.debug("未序列化 {}", loginUser);
        log.debug("序列化 {}", JSONUtil.toJsonStr(loginUser));

        log.debug("序列化 角色: {}", JSONUtil.toJsonStr(loginUser.getAuthorities().toString()));
        SaveLoginUser saveLoginUser = new SaveLoginUser();
        BeanUtils.copyProperties(loginUser,saveLoginUser);
        // 存储到Redis
        jwtUtil.storeUserWithToken("token_"+loginUser.getUsername(), saveLoginUser);

        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);

        return JsonResult.ok(map);
    }




//    注册
    @PostMapping("/register")
    public JsonResult register(@RequestBody User user) {
        log.debug("register user: {}", user);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return JsonResult.ok(userMapper.registerUser(user)==1?"注册成功":"注册失败");
    }


    @PostMapping("/test")
    public JsonResult test() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SaveLoginUser loginUser = (SaveLoginUser) authentication.getPrincipal();
        log.debug("test loginUser: {}", loginUser);
        return JsonResult.ok(loginUser);
    }
}